package TCP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class Server {
    public static HashMap<String,String> hashMap = new HashMap<>();

    public static void start(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        DataInputStream dis = new DataInputStream(inputStream);
        OutputStream os = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        while (true) {

            try {
                String str = dis.readUTF();
                System.out.println( "来自主机IP地址为: "+socket.getInetAddress().getHostAddress() + " ,端口号为: "+ socket.getPort() + " :" + str);

                putData();
                String s = send(str);
                String ret = select(s);
                if (ret == null){
                    ret = "输出错误!!!";
                }
                dos.writeUTF(ret);
                System.out.println("==========================");
            } catch (IOException e) {
                System.out.println( socket.getInetAddress().getHostAddress() + "离线啦!!!");
                dos.close();
                dis.close();
                socket.close();
                break;
            }

        }
    }
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9090);
        Socket socket = serverSocket.accept();
        while (true) {
            new Thread(() -> {
                try {
                    start(socket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }


    }
    private static String select(String s){
        return hashMap.get(s);
    }
    private static void putData(){
        hashMap.put("小狗","dog");
        hashMap.put("小猫","cat");
        hashMap.put("猪","pig");
        hashMap.put("鸟","bird");
        hashMap.put("鱼","fish");
    }
    private static String send(String str){
        return str;
    }

}
